<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()" ref="dataForm">
      <el-form-item>
        <el-select v-model="dataForm.orderStatus" placeholder="请选择类别">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.belongGrade" placeholder="请选择会员身份">
          <el-option
            v-for="item in useroption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.bigbayAppId" placeholder="请选择售出类别">
          <el-option
            v-for="item in projectList"
            :key="item.bigbayAppId"
            :label="item.bigbayAppName"
            :value="item.bigbayAppId"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="日期和时间范围："> -->
      <el-select
        style="width:120px;"
        @change="dateChanged"
        v-model="searchData.currentDate"
        placeholder="请选择时间"
      >
        <el-option v-for="item in dateSelect" :key="item" :label="item" :value="item"></el-option>
      </el-select>
      <template v-if="showDatePicker">
        <el-date-picker
          style="width:220px;"
          v-model="searchData.startDate"
          type="date"
          value-format="yyyy-MM-dd "
          placeholder="开始时间"
        ></el-date-picker>~
        <el-date-picker
          style="width:220px;"
          v-model="searchData.endDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="结束时间"
        ></el-date-picker>
      </template>
      <el-button @click="search()">查询</el-button>
      <el-button type="primary" @click="download()">下载</el-button>
      <!-- </el-form-item> -->
    </el-form>
    <div class="winNumber">
      <span>总订单数：{{orderNum}}笔</span>
      <span>总销售额：{{totalVolume}}元</span>
      <span>总会员收益：{{totalRevenue}}元</span>
    </div>
    <el-table :data="dataList" border v-loading="dataListLoading" style="width: 100%;">
      <el-table-column prop="gmtCreate" header-align="center" align="center" label="日期">
        <template slot-scope="scope">
          <span>{{ scope.row.gmtCreate.split(' ')[0] }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" header-align="center" align="center" label="类别">
        <template slot-scope="scope">{{scope.row.orderStatus=='1'?'售出业绩':'退款'}}</template>
      </el-table-column>
      <el-table-column prop="belongGrade" header-align="center" align="center" label="会员身份">
        <template slot-scope="scope">
          {{scope.row.belongGrade=='1'?'会员':''}}
          {{scope.row.belongGrade=='2'?'经理':''}}
          {{scope.row.belongGrade=='3'?'总监':''}}
          {{scope.row.belongGrade=='4'?'全部':''}}
        </template>
      </el-table-column>
      <el-table-column prop="saleTypeName" header-align="center" align="center" label="售出类别"></el-table-column>
      <el-table-column prop="orderNum" header-align="center" align="center" label="订单/笔"></el-table-column>
      <el-table-column prop="totalVolume" header-align="center" align="center" label="销售额/元"></el-table-column>
      <el-table-column prop="totalRevenue" header-align="center" align="center" label="会员收益/元"></el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      options: [
        {
          value: "1",
          label: "售出业绩"
        },
        {
          value: "-1",
          label: "全部退款"
        }
      ],
      useroption: [
        {
          value: "1",
          label: "会员"
        },
        {
          value: "2",
          label: "经理"
        },
        {
          value: "3",
          label: "总监"
        },
        {
          value: "4",
          label: "全部"
        }
      ],
      dataForm: {
        belongGrade: "4",
        orderStatus: "1",
        bigbayAppId: 1
      },
      searchData: {
        projects: [],
        currentDate: "昨日",
        startDate: "",
        endDate: ""
      },
      projectList: [],
      dateSelect: ["昨日", "本周", "上周", '本月', "最近30天", "上月", "自定义"],
      showDatePicker: false,
      dataList: [],
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      value: "",
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      orderNum: "",
      totalRevenue: "",
      totalVolume: ""
    };
  },
  mounted() {
    let obj = {
      preDay: 1,
      day: 0
    };
    let timeDate = this.getDateData(obj);
    this.searchData.startDate = timeDate.startDate;
    this.searchData.endDate = timeDate.endDate;
    this.getClassList();
  },
  activated() {
    this.getDataList();
    // this.getmoney();
  },
  methods: {
    //时间select change事件
    dateChanged(val) {
      let obj = {};
      if (val === "昨日") {
        obj.preDay = 1;
        obj.day = 0;
      } else if (val === "本周") {
        let num = new Date().getDay();
        if (num === 0) {
          obj.preDay = 6;
          obj.day = 6;
        } else {
          obj.preDay = num-1;
          obj.day = 6;
        }
      } else if (val === "上周") {
        let num = new Date().getDay() === 0 ? 7 : new Date().getDay();
        obj.preDay = num + 6;
        obj.day = 6;
      } else if (val === "本月") {
        let num = new Date().getDate();
        obj.preDay = num - 1;
        obj.day = num - 1;
      } else if (val === "最近30天") {
        obj.preDay = 29;
        obj.day = 29;
      } else if (val === "上月") {
        let date = new Date();
        date.setDate(0);
        console.log(date)
        let monthNum = date.getDate();
        let num = monthNum + new Date().getDate();
        obj.preDay = num-1;
        obj.day = monthNum-1;
      }

      if (val === "自定义") {
        this.searchData.startDate = "";
        this.searchData.endDate = "";
        this.showDatePicker = true;
        return;
      } else {
        let timeDate = this.getDateData(obj);
        console.log("timeDate====>", timeDate);
        this.searchData.startDate = timeDate.startDate;
        console.log("this.searchData.endDate====>", timeDate.endDate);
        this.searchData.endDate = timeDate.endDate;
        // if (val === "本周" || val === "最近30天") {
        //   this.searchData.endDate = new Date();
        // } else {
        //   this.searchData.endDate = timeDate.endDate;
        // }
      }
      this.showDatePicker = false;
    },
    getDateData(data) {
      let obj = {};
      obj.startDate = "";
      obj.endDate = "";
      if (data && data.preDay + "") {
        let time = Date.now();
        let startDate = getDateText(time - data.preDay * 24 * 3600 * 1000);
        let endDate = getDateText(
          time - data.preDay * 24 * 3600 * 1000 + data.day * 24 * 3600 * 1000
        );
        obj.startDate = startDate;
        obj.endDate = endDate;
      }

      function getDateText(timeMinutes) {
        let date = new Date(timeMinutes);
        let year = date.getFullYear();
        let month =
          date.getMonth() > 8
            ? date.getMonth() + 1
            : "0" + (date.getMonth() + 1);
        let dayText =
          date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
        console.log(dayText);
        return year + "-" + month + "-" + dayText;
      }
      return obj;
    },
    //获取课程
    getClassList() {
      this.$http({
        url: this.$http.adornUrl("/saleStatistic/AppInfo/list"),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data);
          this.projectList = data.list;
        }
      });
    },
    search(){
      this.pageIndex = 1;
      this.getDataList();
    },
    //获取总金额
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true;
      let obj = {
        page: this.pageIndex,
        limit: this.pageSize
      };
      obj.startDate = this.searchData.startDate;
      obj.endDate = this.searchData.endDate;
      obj.belongGrade = this.dataForm.belongGrade;
      obj.orderStatus = this.dataForm.orderStatus;
      obj.saleType = this.dataForm.bigbayAppId;
      this.$http({
        url: this.$http.adornUrl("/saleStatistic/salestatistics/list"),
        method: "get",
        params: this.$http.adornParams(obj)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$refs["dataForm"].resetFields();
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
      this.$http({
        url: this.$http.adornUrl(
          "/saleStatistic/salestatistics/getStatisticByCondition"
        ),
        method: "get",
        params: this.$http.adornParams(obj)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.orderNum = data.totalStatistic.orderNum;
          this.totalRevenue = data.totalStatistic.totalRevenue;
          this.totalVolume = data.totalStatistic.totalVolume;
        }
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    download() {
      // if (this.totalPage == 0) {
      //   this.$notify({
      //     title: "提示",
      //     message: "下载失败！无检索数据！",
      //     type: "error",
      //     offset: 100
      //   });
      //   return;
      // }
      // console.log(this.dataForm)
      let obj = {
        page: this.pageIndex,
        limit: this.pageSize
      };
      // if (this.searchData.currentDate) {
      obj.startDate = this.searchData.startDate;
      obj.endDate = this.searchData.endDate;
      // }
      // if (this.dataForm.belongGrade && this.dataForm.belongGrade !== "4") {
      obj.belongGrade = this.dataForm.belongGrade;
      // }
      // if (this.dataForm.orderStatus && this.dataForm.orderStatus != '0') {
      obj.orderStatus = this.dataForm.orderStatus;
      // }
      // if (this.dataForm.courseId && this.dataForm.courseId != null) {
      obj.saleType = this.dataForm.bigbayAppId;
      this.$http({
        url: this.$http.adornUrl("/saleStatistic/salestatistics/download"),
        method: "get",
        params: this.$http.adornParams(obj),
        headers: {
          "Content-Type": "application/json; application/octet-stream"
        },
        responseType: "arraybuffer"
      }).then(({ data }) => {
        const blob = new Blob([data], { type: "application/vnd.ms-excel" });
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = "业绩统计.xls";
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
      });
      // window.location.href =
      //   window.SITE_CONFIG["baseUrl"] +
      //   "/saleStatistic/salestatistics/download?orderStatus=" +
      //   this.dataForm.orderStatus +
      //   "&startDate=" +
      //   this.searchData.startDate +
      //   "&endDate=" +
      //   this.searchData.endDate +
      //   "&belongGrade=" +
      //   this.dataForm.belongGrade +
      //   "&saleType=" +
      //   this.dataForm.courseId
    }
  }
};
</script>
<style lang="scss" scoped>
.winNumber {
  color: #777;
  margin-bottom: 20px;
  span {
    margin-right: 20px;
  }
}
</style>

